<?php

namespace app\admin\controller\material;

use app\admin\model\Course;
use app\common\controller\Backend;
use think\Db;
use think\db\exception\DataNotFoundException;
use think\db\exception\ModelNotFoundException;
use think\Exception;
use think\exception\DbException;
use think\response\Json;

/**
 * 资料分类
 *
 * @icon fa fa-circle-o
 */
class Category extends Backend
{

    /**
     * Category模型对象
     * @var \app\admin\model\material\Category
     */
    protected $model = null;

    /**
     * Course模型对象
     * @var Course
     */
    protected $courseModel = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->courseModel = new Course();
        $this->model = new \app\admin\model\material\Category();
    }

    /**
     * 列表
     * @return string|Json
     * @throws Exception
     * @throws DbException
     */
    public function index()
    {
        // 请求参数
        $param = $this->request->param();

        // 提取参数
        $pid = $param['pid'] ?? 0;
        $course_id = $param['course_id'] ?? 0;

        // 设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $otherWhere = [];
            $otherWhere['pid'] = $pid;
            if ($course_id) {
                $otherWhere['course_id'] = $course_id;
            }
            $list = $this->model
                ->where($where)
                ->where($otherWhere)
                ->order($sort, $order)
                ->paginate($limit);
            $list = $list ? $list->toArray() : [];
            $rows = $list['data'];
            $result = array("total" => $list['total'], "rows" => $rows);

            return json($result);
        }

        // 父类上级Id
        $pidPid = 0;
        if ($pid) {
            $pidPid = $this->model->where(['id' => $pid])->value('pid', 0);
        }

        // 查看课程信息
        $courseName = '';
        if ($course_id) {
            $courseName = $this->courseModel->where(['id' => $course_id])->value('name', '');
        }

        // 生成导航
        $allLiList = $this->buildNavHtml($pid, $course_id);
        $allLiList = array_reverse($allLiList);

        // 注入变量
        $this->view->assign('pid', $pid);
        $this->view->assign('course_id', $course_id);
        $this->view->assign('pidPid', $pidPid);
        $this->view->assign('courseName', $courseName);
        $this->view->assign('allLiList', $allLiList);
        return $this->view->fetch();
    }

    /**
     *  生成导航Html
     * @param $pid
     * @param $courseId
     * @return array
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    private function buildNavHtml($pid, $courseId): array
    {
        $allParent = $this->model->getAllParent($pid);
        $allLi = [];
        $baseDom = '<li><a href="%s">%s</a></li>';
        $baseUrl = "/material/category/index/pid/%s/course_id/%s";
        foreach ($allParent as $parent) {
            $url = sprintf($baseUrl, $parent['id'], $parent['course_id']);
            $dom = sprintf($baseDom, $url, $parent['name']);
            $allLi[] = $dom;
        }

        $url = sprintf($baseUrl, 0, $courseId);
        $dom = sprintf($baseDom, $url, '根分类');
        $allLi[] = $dom;
        return $allLi;
    }

    /**
     *  添加分类
     * @return string
     * @throws Exception
     * @throws DataNotFoundException
     * @throws ModelNotFoundException
     * @throws DbException
     */
    public function add()
    {
        // 请求参数
        $param = $this->request->param();

        // 提取参数
        $pid = $param['pid'] ?? 0;
        $course_id = $param['course_id'] ?? 0;

        // 查询是否创建子分类
        $parentRow = null;
        if ($pid) {
            $parentRow = $this->model->find($pid);
        }

        // 创建分类逻辑
        if ($this->request->isPost()) {
            // 请求参数
            $rowParam = $param['row'] ?? [];

            // 检查数据
            if (!$rowParam) {
                $this->error('请求参数不得为空');
            }

            // 提取参数
            $pid = $rowParam['pid'] ?? 0;
            $name = $rowParam['name'] ?? 0;
            $name = trim($name);
            $course_id = $rowParam['course_id'] ?? 0;
            if (!$course_id) {
                $this->error('所属课程不得为空');
            }

            // 重复判断
            $where = [
                'pid' => $pid,
                'name' => $name,
                'course_id' => $course_id,
            ];
            $count = $this->model->where($where)->count();
            if ($count) {
                $this->error('存在相同名称的分类');
            }

            // 保存数据
            $saveData = [
                'pid' => $pid,
                'name' => $name,
                'course_id' => $course_id,
            ];
            $isAdd = $this->model->save($saveData);
            if (!$isAdd) {
                $this->error('创建失败');
            }
            $this->success();
        }

        // 注册变量
        $this->view->assign('pid', $pid);
        $this->view->assign('course_id', $course_id);
        $this->view->assign('parentRow', $parentRow);
        return $this->view->fetch();
    }

}
